package com.example.server.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.server.web.domain.*;
import com.example.server.web.domain.Class;
import com.example.server.web.exception.CustomException;
import com.example.server.web.mapper.StudentQuestionnaireMapper;
import com.example.server.web.service.*;
import com.example.server.web.mapper.FactTableMapper;
import com.example.server.web.utils.MyObjectUtils;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
* @author YHJ
* @description (事实表) 服务实现类
*/
@Service
public class FactTableServiceImpl extends ServiceImpl<FactTableMapper, FactTable>
    implements FactTableService{

    @Autowired
    private AcademyService academyService;

    @Autowired
    private StudentQuestionnaireService studentQuestionnaireService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private ClassService classService;

    @Resource
    private FactTableMapper factTableMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private QuestionnaireSummaryService summaryService;

    @Autowired
    private MajorService majorService;

    @Resource
    private StudentQuestionnaireMapper studentQuestionnaireMapper;

    @Autowired
    private CourseClassTeacherService courseClassTeacherService;

    @Override
    public void countQuestionnaireData(Questionnaire questionnaire) {
        if (ObjectUtils.isEmpty(questionnaire)){
            return;
        }
        //查询代码等信息
        FactTable factTable = new FactTable();
        factTable.setEvalTime(questionnaire.getYear());
        factTable.setQuestId(questionnaire.getId());
        //查询班级
        Class aClass = classService.getById(questionnaire.getClassId());
        MyObjectUtils.throwExIfNull(aClass,"该班级不存在");
        factTable.setGrade(aClass.getGrade());

        //查询专业
        Major major = majorService.getById(aClass.getMajorId());
        MyObjectUtils.throwExIfNull(major,"该专业不存在");
        factTable.setMajor(major.getCode());

        //查询学院
        Academy academy = academyService.getById(aClass.getAcademyId());
        MyObjectUtils.throwExIfNull(academy,"该学院不存在");
        factTable.setDept(academy.getCode());

        //查询课程
        Course course = courseService.getById(questionnaire.getCourseId());
        MyObjectUtils.throwExIfNull(course,"该课程不存在");
        factTable.setClass2(course.getCode());

        //查询课程-班级-教师关联
        // LambdaQueryWrapper<CourseClassTeacher> queryWrapper = new LambdaQueryWrapper<>();
        // queryWrapper.eq(CourseClassTeacher::getClassId,questionnaire.getClassId());
        // queryWrapper.eq(CourseClassTeacher::getCourseId,questionnaire.getCourseId());
        MyObjectUtils.throwExIfNull(questionnaire.getCctId(),"该问卷对应的关联课程不存在");
        CourseClassTeacher courseClassTeacher = courseClassTeacherService.getById(questionnaire.getCctId());
        if (ObjectUtils.isNotEmpty(courseClassTeacher)){
            factTable.setTeachId(courseClassTeacher.getTeacherId());
        }

        //获取学生填写记录
        List<StudentQuestionnaire> studentQuestionnaires = studentQuestionnaireMapper.selectList(new LambdaQueryWrapper<StudentQuestionnaire>()
                .eq(StudentQuestionnaire::getQuestionnaireId, questionnaire.getId()));

        //每个学生的教学态度分数平均分总和
        BigDecimal attitudeScoreSum = BigDecimal.ZERO;
        //每个学生的教学内容分数平均分总和
        BigDecimal contentScoreSum = BigDecimal.ZERO;
        //每个学生的教学方法分数平均分总和
        BigDecimal methodScoreSum = BigDecimal.ZERO;
        //每个学生的教学效果分数平均分总和
        BigDecimal resultScoreSum = BigDecimal.ZERO;
        //每个学生的总分分数平均分总和
        BigDecimal totalScoreSum = BigDecimal.ZERO;
        //计算学生填写分数
        for (StudentQuestionnaire studentQuestionnaire : studentQuestionnaires) {
            FactTable table = new FactTable();
            BeanUtils.copyProperties(factTable,table);
            table.setStuId(studentQuestionnaire.getUserId());

            //获取教学态度均分
            BigDecimal teaAttitudeOne = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaAttitudeOne(), BigDecimal.ZERO);
            BigDecimal teaAttitudeTwo = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaAttitudeTwo(), BigDecimal.ZERO);
            //计算
            BigDecimal attitudeScore = teaAttitudeOne.add(teaAttitudeTwo).divide(BigDecimal.valueOf(2),2,RoundingMode.HALF_UP);
            table.setAttitudeScore(attitudeScore);
            attitudeScoreSum = attitudeScoreSum.add(attitudeScore);

            //获取教学内容均分
            BigDecimal teaContentOne = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaContentOne(), BigDecimal.ZERO);
            BigDecimal teaContentTwo = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaContentTwo(), BigDecimal.ZERO);
            BigDecimal teaContentThree = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaContentThree(), BigDecimal.ZERO);
            //计算
            BigDecimal contentScore = teaContentOne.add(teaContentTwo).add(teaContentThree).divide(BigDecimal.valueOf(3), 2,RoundingMode.HALF_UP);
            table.setContentScore(contentScore);
            contentScoreSum = contentScoreSum.add(contentScore);

            //获取教学方法均分
            BigDecimal teaMethodOne = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaMethodOne(), BigDecimal.ZERO);
            BigDecimal teaMethodTwo = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaMethodTwo(), BigDecimal.ZERO);
            //计算
            BigDecimal methodScore = teaMethodOne.add(teaMethodTwo).divide(BigDecimal.valueOf(2),2,RoundingMode.HALF_UP);
            table.setMethodScore(methodScore);
            methodScoreSum = methodScoreSum.add(methodScore);

            //获取教学效果均分
            BigDecimal teaEffectOne = MyObjectUtils.defaultIfNull(studentQuestionnaire.getTeaEffectOne(), BigDecimal.ZERO);
            //计算
            BigDecimal resultScore = teaEffectOne;
            table.setResultScore(resultScore);
            resultScoreSum = resultScoreSum.add(resultScore);

            //总分
            BigDecimal score1 = attitudeScore.multiply(BigDecimal.valueOf(0.2));
            BigDecimal score2 = contentScore.multiply(BigDecimal.valueOf(0.3));
            BigDecimal score3 = methodScore.multiply(BigDecimal.valueOf(0.2));
            BigDecimal score4 = resultScore.multiply(BigDecimal.valueOf(0.3));
            BigDecimal totalScore = score1.add(score2).add(score3).add(score4);
            table.setTotalScore(totalScore.doubleValue());
            totalScoreSum = totalScoreSum.add(totalScore);

            //获取等级
            String level = getLevel(totalScore);
            //设置等级
            table.setLevel(level);

            int insert = factTableMapper.insert(table);
            if (insert < 1){
                throw new CustomException("系统发生了错误，请联系管理员");
            }
        }
        //获得学生填写问卷记录的条数
        int num = studentQuestionnaires.size();
        if (num > 0){
            //赋值
            QuestionnaireSummary summary = new QuestionnaireSummary();
            summary.setAcademyId(academy.getId());
            summary.setAcademyName(academy.getAcademyName());
            summary.setClassId(aClass.getId());
            summary.setClassName(aClass.getClassName());
            summary.setMajorId(major.getId());
            summary.setMajorName(major.getName());
            summary.setCourseId(course.getId());
            summary.setCourseName(course.getCourseName());
            summary.setYear(questionnaire.getYear());
            if (ObjectUtils.isNotEmpty(courseClassTeacher)){
                summary.setTeacherId(courseClassTeacher.getTeacherId());
            }
            //获取教师名称
            if (ObjectUtils.isNotEmpty(courseClassTeacher)){
                Long teacherId = courseClassTeacher.getTeacherId();
                factTable.setTeachId(teacherId);
                String teacherName = teacherService.getTeacherName(teacherId);
                summary.setTeacherName(teacherName);
            }
            summary.setAttitudeScore(attitudeScoreSum.divide(BigDecimal.valueOf(num),2,RoundingMode.HALF_UP));
            summary.setContentScore(contentScoreSum.divide(BigDecimal.valueOf(num),2,RoundingMode.HALF_UP));
            summary.setMethodScore(methodScoreSum.divide(BigDecimal.valueOf(num),2,RoundingMode.HALF_UP));
            summary.setResultScore(resultScoreSum.divide(BigDecimal.valueOf(num),2,RoundingMode.HALF_UP));
            summary.setTotalScore(totalScoreSum.divide(BigDecimal.valueOf(num),2,RoundingMode.HALF_UP));
            boolean save = summaryService.save(summary);
            if (!save){
                throw new CustomException("新增问卷汇总失败，请联系管理员");
            }
        }
    }


    /**
     * 获取等级
     * @param totalScore
     * @return
     */
    private String getLevel(BigDecimal totalScore) {
        //判断等级
        String level = null;
        if (totalScore.compareTo(BigDecimal.valueOf(9)) > 0){
            level = "A";
        } else if (totalScore.compareTo(BigDecimal.valueOf(8)) > 0){
            level = "B";
        } else if (totalScore.compareTo(BigDecimal.valueOf(7)) > 0){
            level = "C";
        } else {
            level = "D";
        }
        return level;
    }

    @Override
    public List<FactTable> queryAllDataByYear(String year) {
        List<FactTable> factTableList = factTableMapper.selectListByYear(year);
        return factTableList;
    }
}




